import router from "@/router";
import { useUserStore } from "./stores/user";
import pinia from "@/stores";
import NProgress from "nprogress";
import "nprogress/nprogress.css";

/**
 * 每一个仓库内部会调用 pinia 实例
 * 组件直接可以访问：我们把 pinia 实例通过 app.use() 已经注册到组件中
 * 在非组件的环境下需要手动去指定 pinia 实例，并传入给 use 方法
 */
const userStore = useUserStore(pinia);

// 路由白名单
const whiteList = ["/login", "/404"];

router.beforeEach(async (to, from, next) => {
  NProgress.start();
  const redirectPath: string = to.query.redirect as string;
  if (userStore.token) {
    if (to.path == "/login") {
      return next(redirectPath ? redirectPath : { name: "HomeIndex" });
    }
    if (userStore.userInfo.name) {
      next();
    } else {
      console.log("发送请求获取用户基本信息");
      try {
        await userStore.getMine();
        next();
      } catch (e) {
        alert("token有问题");
        next("/login");
      }
    }
  } else {
    if (whiteList.includes(to.path)) {
      next();
    } else {
      next("/login");
    }
  }
});

router.afterEach(() => {
  NProgress.done();
});
